package com.javaweb.servlet;

import com.javaweb.common.DBUtil;
import com.javaweb.common.DispatcherTool;
import com.javaweb.common.FileUploadTool;
import com.javaweb.common.StringTool;
import com.javaweb.entity.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.File;
import java.io.IOException;

/**
 * the servlet for user register
 */
@WebServlet(name="register",
            urlPatterns = {"/register"}
)
@MultipartConfig(
        fileSizeThreshold = 0 , // for controlling cache.
        maxRequestSize = 1024 * 1024, //
        maxFileSize = 1024 * 1024
)
public class RegisterServlet  extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp) ;
     }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        /**
         * 文件上传逻辑：
         * 1. 设置内容编码
         * 2. 拿到Part对象
         * 3. 检查文件类型是否合规
         * 4. 设置文件存储的文件夹名，文件改名。
         * 5. part.write将上传数据写入文件
         */
        req.setCharacterEncoding(StringTool.UTF);
        String name = req.getParameter("name") ;
        String pwd = req.getParameter("pwd") ;
        String secondPwd = req.getParameter("secondPwd") ;


        if (StringTool.isEmpty(name, pwd, secondPwd)) {
            DispatcherTool.indirectForwardToClient(req, resp,
                                                   "01/servlet/login.jsp", "参数为空！");
            return ;
        }
        // check the name was a new name
        if (DBUtil.existedName(name)) {
            DispatcherTool.indirectForwardToClient(req, resp,
                    "01/servlet/login.jsp", "用户名已存在！");
            return ;
        }
        /**
         * write the uploaded data into the file.
         */
        Part part = req.getPart("userImage") ;
        if (! FileUploadTool.isImage(part.getContentType())) {
            DispatcherTool.indirectForwardToClient(req, resp,
                    "01/servlet/login.jsp", "文件类型不正确！");
            return ;
        }
        String targetDir = FileUploadTool.getAbsoluteUploadDir(req) ;
        String newFileName = FileUploadTool.newFileName(part.getSubmittedFileName()) ;
        String newFullName = targetDir + File.separator + newFileName ;
        try {
            part.write(newFullName);
        }catch (IOException e) {
            e.printStackTrace();
            DispatcherTool.indirectForwardToClient(req, resp,
                                            "01/servlet/login.jsp",
                                            "文件上传失败！");
            return ;
        }
        System.out.println("[INFO] RegisterServlet: upload successfully." ) ;
        /*
        save the user to DB
         */
        int ret = DBUtil.addNewUser(name, pwd, newFullName) ;
        if (ret > 0) {
            // OK
            System.out.println("[IFNO] RegisterServlet: register OK.") ;
            HttpSession session = req.getSession() ;
            session.setAttribute("user", new User(name, pwd, newFileName));
            DispatcherTool.indirectForwardToClient(req, resp, "01/servlet/welcome.jsp", "注册成功！");

        } else {
            // not OK
            System.out.println("[IFNO] RegisterServlet: register failed.") ;
            DispatcherTool.indirectForwardToClient(req, resp, "01/servlet/welcome.jsp", "注册失败！");
        }

    }

}
